﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.UI;
using System.Collections.Generic;
using Microsoft.Office.Server.UserProfiles;
using System.Collections;

namespace Trig_AMJ_HR_Forms.Layouts.Trig_AMJ_HR_Forms
{

    //http://www.designkindle.com/2011/10/07/build-icons/
    //http://webdesignledger.com/freebies/50-amazing-free-icon-sets
    //http://speckyboy.com/2012/12/17/top-50-free-icon-sets-from-2012/

    public partial class Personnel_Action_Print : LayoutsPageBase
    {
        SPHelper obj = new SPHelper();
        Demand_Voucher_FormClass demandVoucherclass = new Demand_Voucher_FormClass(); // Helper class for this solution
        Trig_WF trigWFClass = new Trig_WF();

        decimal PrevgrdTotal = 0;
        decimal PresgrdTotal = 0;

        #region "Properties"

        string CurrentUser = SPContext.Current.Web.CurrentUser.LoginName;

        public static string SiteURL;
        public static string PARequestNo;
        public static string MainLstName;
        public static string TaskLstName;
        public static string AttLibName;
        public static string CmntsLstName;
        public static string WorkflowConfigList;

        public static string ActionClassifications;

        public static string ActionDetails;

        public static string Nationalities;
        public static string ActionTypes;
        public static string Divisions;
        public static string Designations;

        public static string lstGuid;
        public string camlQry;
        public SPQuery qry;
        public static string Mode;
        public static string TaskItemID;
        public static string submittedfor;
        string ErrorMsgs;
        public static int wfOrder = 0;
        public static string DocumentTypesList;
        public static string WFCurrentOrder = string.Empty;
        string WFTaskType = string.Empty;

        public static string refID;
        public static int PAItemID;

        public static bool Binding = true;

        string[] buttonVisibilty = new string[5];

        private static SPListItemCollection oItemsColl = null;
        private static SPListItem oItems = null;

        public static string ActionType;

        private int isDuplicateNo;
        private bool isDuplicateClassName = false;

        List<string> strListSpecification = new List<string>();

        public string evtHandler;

        #endregion


        public Personnel_Action_Print()
        {
            SiteURL = SPContext.Current.Site.Url;
            SiteURL = SiteURL + "/sites/forms/";
            MainLstName = "Personnel Action Forms";
            TaskLstName = "Personnel Action Tasks";
            CmntsLstName = "Personnel Action Comments";
            AttLibName = "Attachments";
            WorkflowConfigList = "Workflow Configuration List";
            DocumentTypesList = "DocumentTypes";

            ActionClassifications = "Personnel Action Classifications";
            Nationalities = "Nationalities";
            ActionTypes = "Personnel Action Types";
            ActionDetails = "Personnel Action Details";
            Divisions = "Divisions";
            Designations = "Designations";

        }


        protected void Page_Load(object sender, EventArgs e)
        {


            if (!IsPostBack)
            {
                Mode = Request.QueryString["Mode"];
                refID = Request.QueryString["RefID"]; // From Dashboard.
                TaskItemID = Convert.ToString(Request.QueryString["TaskItemID"]);
                // Bind Values in All DropDown Lists

                if (Mode == "Print" || Mode == "View")
                {
                    ReLoadDetails();
                }
                else
                {
                    pnlFullForm.Visible = false;
                    pnlAccessDenied.Visible = true;
                    lblAccessDeniedMsg.Visible = true;
                    lblAccessDeniedMsg.Text = "Unable to open the form. Value is missing. Contact administrator";
                }
            }

        }


        #region Bind In DropDown Controls


        private void GetClassifications()
        {
            try
            {
                DropDownList ddlSpecification = gvSalaryInfo.Rows[0].FindControl("ddlSpecification") as DropDownList;
                BindInDropDown(ActionClassifications, ddlSpecification);
                ddlSpecification.Items.Insert(0, "Select");

            }
            catch (Exception)
            {

            }


        }


        #endregion

        /// <summary>
        /// GridView row databound event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvSalaryInfo_RowDataBound(object sender, GridViewRowEventArgs e)
        {

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                int rowIndex = Convert.ToInt32(e.Row.DataItemIndex);
                evtHandler = "updateValue(this," + rowIndex + ",1)";
                TextBox txtRate = (TextBox)e.Row.FindControl("txtPrevious");
                txtRate.Attributes.Add("onkeyup", evtHandler);   //onkeyup  //onchange
                TextBox txtQuantity = (TextBox)e.Row.FindControl("txtPresent");
                txtQuantity.Attributes.Add("onkeyup", evtHandler);
            }

        }




        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {

            if (e.Row.RowType == DataControlRowType.Footer)
            {
                Label lblPreviousTtls = (Label)e.Row.FindControl("lblPreviousTtl");
                Label lblPresentTtls = (Label)e.Row.FindControl("lblPresentTtl");
                lblPreviousTtls.Text = PrevgrdTotal.ToString();//.ToString("c");
                lblPresentTtls.Text = PresgrdTotal.ToString();//.ToString("c");
            }
        }



        private decimal g(GridViewRowEventArgs e)
        {
            decimal rowTotal;
            try
            {
                TextBox txtPrev = (TextBox)e.Row.FindControl("txtPrevious");
                rowTotal = Convert.ToDecimal(txtPrev.Text);
            }
            catch (Exception)
            {
                rowTotal = 0;
            }
            return rowTotal;
        }

        /// <summary>
        /// Assign datasource to gridview 
        /// </summary>
        /// <returns></returns>

        private DataTable GetGridViewDataSource()
        {
            DataTable dt2 = new DataTable();
            try
            {
                dt2.Columns.Add("Classification", typeof(string));
                dt2.Columns.Add("Previous", typeof(string));
                dt2.Columns.Add("Present", typeof(string));

                if (gvSalaryInfo.Rows.Count > 0)
                {
                    SPFieldLookupValue ofldlook = null;
                    for (int i = 0; i < gvSalaryInfo.Rows.Count; i++)
                    {
                        DropDownList ddlClass = (DropDownList)gvSalaryInfo.Rows[i].FindControl("ddlSpecification");
                        DataRow dr1 = dt2.NewRow();
                        ofldlook = new SPFieldLookupValue(ddlClass.SelectedValue);
                        dr1["Classification"] = ofldlook.LookupId;
                        TextBox txtPrevious = (TextBox)gvSalaryInfo.Rows[i].FindControl("txtPrevious");
                        dr1["Previous"] = txtPrevious.Text;
                        PrevgrdTotal = PrevgrdTotal + Convert.ToDecimal(txtPrevious.Text);

                        TextBox txtPresent = (TextBox)gvSalaryInfo.Rows[i].FindControl("txtPresent");
                        dr1["Present"] = txtPresent.Text;
                        PresgrdTotal = PresgrdTotal + Convert.ToDecimal(txtPresent.Text);
                        dt2.Rows.Add(dr1);

                    }

                }
            }
            catch (Exception ex)
            {
                //exceptionHandler.GenerateExceptionLog("Trig_AMJ_AMG_Forms:: Demand_Voucher_Form::GetGridViewDataSource", "Exception in catch block", ex.Message);
            }
            return dt2;
        }

        /// <summary>
        /// set values to Grid view
        /// </summary>
        /// <param name="dt2"></param>


        private void SetGridViewValues(DataTable dt2)
        {
            DataRow drGetRow;
            SPFieldLookupValue ofldlook = null;

            decimal rowTotal;

            for (int i = 0; i < dt2.Rows.Count; i++)
            {
                drGetRow = dt2.Rows[i];

                DropDownList ddlClass = (DropDownList)gvSalaryInfo.Rows[i].FindControl("ddlSpecification");
                ofldlook = new SPFieldLookupValue(Convert.ToString(drGetRow["Classification"]));
                BindInDropDown(ActionClassifications, ddlClass);
                ddlClass.Items.Insert(0, "Select");

                if (!string.IsNullOrEmpty(Convert.ToString(drGetRow["Classification"])))
                {
                    ofldlook = new SPFieldLookupValue(Convert.ToString(drGetRow["Classification"]));
                    ddlClass.Items.FindByValue(Convert.ToString(ofldlook.LookupId)).Selected = true;
                }

                TextBox txtPrevious = (TextBox)gvSalaryInfo.Rows[i].FindControl("txtPrevious");
                TextBox txtPresent = (TextBox)gvSalaryInfo.Rows[i].FindControl("txtPresent");

                txtPrevious.Text = Convert.ToString(drGetRow["Previous"]);
                txtPresent.Text = Convert.ToString(drGetRow["Present"]);

            }

        }


        private void SetFooterValues()
        {
            foreach (GridViewRow gr in gvSalaryInfo.Rows)
            {
                Label previous = gr.FindControl("txtPrevious") as Label;
                Label present = gr.FindControl("txtPresent") as Label;

                if (!string.IsNullOrEmpty(previous.Text))
                    PrevgrdTotal = PrevgrdTotal + Convert.ToDecimal(previous.Text);
                if (!string.IsNullOrEmpty(present.Text))
                    PresgrdTotal = PresgrdTotal + Convert.ToDecimal(present.Text);
            }

            Label previousTtl = (Label)gvSalaryInfo.FooterRow.FindControl("lblPreviousTtl");
            Label presentTtl = (Label)gvSalaryInfo.FooterRow.FindControl("lblPresentTtl");

            previousTtl.Text = Convert.ToString(PrevgrdTotal);
            presentTtl.Text = Convert.ToString(PresgrdTotal);
        }

        private int CkDuplication()
        {

            for (int i = 0; i < gvSalaryInfo.Rows.Count; i++)
            {
                DropDownList ddlSpecify = (DropDownList)gvSalaryInfo.Rows[i].FindControl("ddlSpecification");
                if (isDuplicateNo > 1)
                {
                    break;
                }
                else
                {
                    isDuplicateNo = 0;
                    for (int j = 0; j < gvSalaryInfo.Rows.Count; j++)
                    {

                        DropDownList ddlSpecification = (DropDownList)gvSalaryInfo.Rows[j].FindControl("ddlSpecification");
                        if (ddlSpecification.SelectedItem.Text.Contains(ddlSpecify.SelectedItem.Text))
                            isDuplicateNo++;
                        if (isDuplicateNo > 1)
                        {
                            isDuplicateClassName = true;

                            TextBox previous = (TextBox)gvSalaryInfo.Rows[j].FindControl("txtPrevious");
                            TextBox present = (TextBox)gvSalaryInfo.Rows[j].FindControl("txtPresent");
                            previous.Text = ""; present.Text = "";
                            previous.ReadOnly = true;
                            present.ReadOnly = true;
                            ScriptManager.RegisterClientScriptBlock(this, GetType(), "Duplication", "alert('Duplicate records are not allowed');", true);
                            break;
                        }
                        if (!isDuplicateClassName)
                        {
                            TextBox previous = (TextBox)gvSalaryInfo.Rows[j].FindControl("txtPrevious");
                            TextBox present = (TextBox)gvSalaryInfo.Rows[j].FindControl("txtPresent");

                            previous.ReadOnly = false;
                            present.ReadOnly = false;
                        }
                    }
                }

            }

            return isDuplicateNo;
        }


        private void Disable_Previous()
        {
            ddlDesigPrev.Enabled = false;
            ddlDivPrev.Enabled = false;

            foreach (GridViewRow gvr in gvSalaryInfo.Rows)
            {
                TextBox txtPrevious = gvr.FindControl("txtPrevious") as TextBox;
                txtPrevious.ReadOnly = true;
            }
        }


        private void BindInDropDown(string SourceListName, DropDownList ddlCntrls)
        {
            ddlCntrls.ClearSelection();
            using (SPSite oSite = new SPSite(SiteURL))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    camlQry = "<Where><IsNotNull><FieldRef Name=\"Title\" /></IsNotNull></Where>";
                    SPList oList = oWeb.Lists.TryGetList(SourceListName);

                    if (oList != null)
                    {
                        ddlCntrls.DataSource = oList.Items.GetDataTable();
                        ddlCntrls.DataTextField = "Title";
                        ddlCntrls.DataValueField = "ID";
                        ddlCntrls.DataBind();
                    }

                }
            }
        }


        private void SetActionDetails()
        {

            foreach (GridViewRow gr in gvSalaryInfo.Rows)
            {
                DropDownList ddlClass = gr.FindControl("ddlSpecification") as DropDownList;
                TextBox txtPrevious = gr.FindControl("txtPrevious") as TextBox;
                TextBox txtPresent = gr.FindControl("txtPresent") as TextBox;
                SetActionDetails(ddlClass, txtPrevious.Text, txtPresent.Text);
            }
        }


        private void SetActionDetails(DropDownList specification, string previous, string present)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {

                string referenceNo = lblActReqNo.Text;
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        SPList oList = oWeb.Lists.TryGetList(ActionDetails);
                        if (oList != null)
                        {
                            SPQuery oEmptyQuery = new SPQuery();
                            oEmptyQuery.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>0</Value></Eq></Where>";
                            SPListItemCollection oItemColl = oList.GetItems(oEmptyQuery);
                            SPListItem oItem = oItemColl.Add();
                            oItem["Title"] = Convert.ToString(referenceNo);

                            string subUser = pplActUser.CommaSeparatedAccounts;
                            //SPUser user = oWeb.EnsureUser(subUser);
                            SPUser User = oWeb.EnsureUser(subUser); //oWeb.SiteUsers[user.Name];
                            SPFieldUserValue SubmittedFor = new SPFieldUserValue(oWeb, User.ID, User.Name);
                            oItem["SubmittedFor"] = SubmittedFor;

                            SPFieldLookupValue fldSpecification = new SPFieldLookupValue(specification.SelectedValue);

                            oItem["Specification"] = fldSpecification.LookupId;
                            oItem["Previous"] = Convert.ToString(previous);
                            oItem["Present"] = Convert.ToString(present);
                            oWeb.AllowUnsafeUpdates = true;
                            oItem.Update();
                            oWeb.AllowUnsafeUpdates = false;
                        }
                    }
                }
            });
        }


        #region "Reload Forms"

        public void ReLoadDetails()
        {
            try
            {
                string RefNo = Convert.ToString(Request.Params["RefID"]);

                if (RefNo != null)
                    camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + refID + "</Value></Eq></Where>";

                SPListItem lstDatas = obj.GetSPListItem(SiteURL, MainLstName, camlQry);
                if (lstDatas != null)
                {

                    lblActReqNo.Text = Convert.ToString(lstDatas["Reference Number"]);
                    dtReqDate.Text = Convert.ToDateTime(lstDatas["RequestDate"]).ToString("dd/MM/yyyy");

                    SetValuesToControls(lstDatas);

                    SetStatusAndClassification(ActionType);
                    SetFooterValues();
                    GetApprovedUsers(RefNo);
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "Parent" + " :: " + "ReLoadDetails";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }


        private void SetValuesToControls(SPListItem lstDatas)
        {
            ArrayList _arrayList;
            txtName.Text = Convert.ToString(lstDatas["Name"]);

            if (Mode != "New")
            {
                SPFieldUserValue fldUser = new SPFieldUserValue(SPContext.Current.Web, Convert.ToString(lstDatas["SubmittedFor"]));
                PickerEntity _pickerEntity = new PickerEntity(); // PickerEntitiy use using Microsoft.SharePoint.WebControls
                _pickerEntity.Key = fldUser.LookupValue;
                _pickerEntity.IsResolved = true;
                _arrayList = new ArrayList();
                _arrayList.Add(_pickerEntity);
                pplActUser.UpdateEntities(_arrayList);
                pplActUser.Enabled = false;
                pplActUsers.Text = fldUser.LookupValue;

                ddlActionType.Text = Convert.ToString(lstDatas["ActionType"]);

            }
            ddlNationality.Text = Convert.ToString(lstDatas["Nationality"]);


            txtEmployeeNo.Text = Convert.ToString(lstDatas["EmployeeID"]);
            dtDOB.Text = Convert.ToDateTime(lstDatas["DOB"]).ToString("dd/MM/yyyy");

            ddlMaritalStatus.Text = Convert.ToString(lstDatas["MaritalStatus"]);

            txtFathersName.Text = Convert.ToString(lstDatas["FathersName"]);
            txtNoDependant.Text = Convert.ToString(lstDatas["NoDependants"]);
            txtAddress.Text = Convert.ToString(lstDatas["Address"]);
            txtTelNo.Text = Convert.ToString(lstDatas["MobileNo"]);
            txtPassportNo.Text = Convert.ToString(lstDatas["PassportNo"]);
            dtPassValidity.Text = Convert.ToDateTime(lstDatas["PassportExpiryOn"]).ToString("dd/MM/yyyy");
            dtDOE.Text = Convert.ToDateTime(lstDatas["DateofEmployment"]).ToString("dd/MM/yyyy");
            txtQadarID.Text = Convert.ToString(lstDatas["QatarID"]);
            dtValofResPermit.Text = Convert.ToDateTime(lstDatas["ResidentPermitValidity"]).ToString("dd/MM/yyyy");

            if (Mode != "New")
            {
                ddlActionType.Text = Convert.ToString(lstDatas["ActionType"]);
                ActionType = Convert.ToString(lstDatas["ActionType"]);
            }

            if (ActionType == "Others")
                txtOthers.Text = Convert.ToString(lstDatas["ActionOthers"]);
            if (ActionType == "Appointment")
                pnlDiv.Visible = false;
            else
                pnlDiv.Visible = true;

        }


        #region "DataBind in 2nd Grid"

        //private void SetStatusAndClassification()
        //{

        //    SPSecurity.RunWithElevatedPrivileges(delegate()
        //    {
        //        using (SPSite oSite = new SPSite(SiteURL))
        //        {
        //            using (SPWeb oWeb = oSite.OpenWeb())
        //            {
        //                if (refID != null)
        //                    camlQry = "<Where><Eq><FieldRef Name=\"Title\" /><Value Type=\"Text\">" + refID + "</Value></Eq></Where>";

        //                oItemsColl = obj.GetSPListItems(SiteURL, ActionDetails, camlQry);
        //                if (oItemsColl != null)
        //                {
        //                    if (oItemsColl.Count > 0)
        //                    {
        //                        int i = 1;

        //                        DataTable dt = new DataTable();
        //                        DataRow dr = null;
        //                        dt.Columns.Add(new System.Data.DataColumn("Class", typeof(string)));
        //                        dt.Columns.Add(new System.Data.DataColumn("Previous", typeof(string)));
        //                        dt.Columns.Add(new System.Data.DataColumn("Present", typeof(string)));


        //                        foreach (SPListItem oItems in oItemsColl)
        //                        {
        //                            if (Convert.ToString(oItems["Specification"]) == "Designation")
        //                            {
        //                                ddlDesigPrev.SelectedItem.Text = Convert.ToString(oItems["Previous"]); ddlDesigPrev.SelectedItem.Selected = true; ddlDesigPrev.Enabled = false;
        //                                ddlDesigPres.SelectedItem.Text = Convert.ToString(oItems["Present"]); ddlDesigPres.SelectedItem.Selected = true; ddlDesigPres.Enabled = false;
        //                            }
        //                            else if (Convert.ToString(oItems["Specification"]) == "Division")
        //                            {
        //                                ddlDivPrev.SelectedItem.Text = Convert.ToString(oItems["Previous"]); ddlDivPrev.SelectedItem.Selected = true; ddlDivPrev.Enabled = false;
        //                                ddlDivPres.SelectedItem.Text = Convert.ToString(oItems["Present"]); ddlDivPres.SelectedItem.Selected = true; ddlDivPres.Enabled = false;
        //                            }

        //                            else
        //                            {

        //                                if (ViewState["CurrentTable"] == null)
        //                                {

        //                                    dr = dt.NewRow();
        //                                    dr["Class"] = Convert.ToString(oItems["Specification"]);
        //                                    dr["Previous"] = Convert.ToString(oItems["Present"]);
        //                                    dr["Present"] = Convert.ToString(oItems["Present"]);
        //                                    PrevgrdTotal = PrevgrdTotal + Convert.ToDecimal(oItems["Present"]);
        //                                    PresgrdTotal = PresgrdTotal + Convert.ToDecimal(oItems["Present"]);
        //                                    dt.Rows.Add(dr);

        //                                }

        //                            }
        //                        }
        //                        GridView1.DataSource = dt;
        //                        GridView1.DataBind();
        //                        ViewState["CurrentTable"] = dt;

        //                    }
        //                }
        //                else
        //                {

        //                }
        //            }
        //        }
        //    });

        //} 

        #endregion

        private void SetStatusAndClassification(string ActionType)
        {
            try
            {

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite oSite = new SPSite(SiteURL))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            PickerEntity pe = (PickerEntity)pplActUser.Entities[0];
                            string ActUser = pe.DisplayText;

                            //if (refID != null) 21-05-2013
                            camlQry = "<Where><And><Eq><FieldRef Name=\"SubmittedFor\" /><Value Type=\"User\">" + ActUser + "</Value>" +
                                "</Eq><IsNull><FieldRef Name=\"Specification\" /></IsNull></And></Where>";
                            oItemsColl = obj.GetSPListItems(SiteURL, ActionDetails, camlQry);
                            if (oItemsColl != null)
                            {
                                if (oItemsColl.Count > 0)
                                {
                                    fnShowDropdownDetails(oItemsColl);
                                }
                            }

                            //if (refID != null) 21-05-2013
                            camlQry = "<Where><And><Eq><FieldRef Name=\"SubmittedFor\" /><Value Type=\"User\">" + ActUser + "</Value>" +
                                "</Eq><IsNotNull><FieldRef Name=\"Specification\" /></IsNotNull></And></Where>";
                            oItemsColl = obj.GetSPListItems(SiteURL, ActionDetails, camlQry);
                            if (oItemsColl != null)
                            {
                                if (oItemsColl.Count > 0)
                                {
                                    fnShowGridDetails(oItemsColl);
                                }
                            }
                        }
                    }
                });
            }
            // }
            catch (Exception)
            {

            }


        }


        #endregion

        /// <summary>
        /// Edit expense details in GridView
        /// </summary>
        /// <param name="oitemcollDraw"></param>
        public void fnShowGridDetails(SPListItemCollection oItemsColl)
        {
            try
            {

                gvSalaryInfo.DataSource = oItemsColl.GetDataTable();
                gvSalaryInfo.DataBind();

            }
            catch (Exception ex)
            {

            }

        }


        public void fnShowDropdownDetails(SPListItemCollection oItemsColl)
        {
            try
            {
                SPFieldLookupValue fldPrev = null;
                SPFieldLookupValue fldPres = null;

                SPFieldLookupValue ofldSpec = null;

                for (int i = 0; i < oItemsColl.Count; i++)
                {

                    oItems = oItemsColl[i];

                    ofldSpec = new SPFieldLookupValue(Convert.ToString(oItems["Specification"]));

                    if (ofldSpec.LookupValue == null)
                    {

                        fldPrev = new SPFieldLookupValue(Convert.ToString(oItems["PreviousDesignation"]));

                        ddlDesigPrev.Text = Convert.ToString(fldPrev.LookupValue);

                        fldPres = new SPFieldLookupValue(Convert.ToString(oItems["PresentDesignation"]));

                        ddlDesigPres.Text = Convert.ToString(fldPres.LookupValue);

                        fldPrev = new SPFieldLookupValue(Convert.ToString(oItems["PreviousDivision"]));
                        fldPres = new SPFieldLookupValue(Convert.ToString(oItems["PresentDivision"]));

                        if (fldPrev.LookupValue != null)
                            ddlDivPrev.Text = Convert.ToString(fldPrev.LookupValue);
                        else
                            ddlDivPrev.Text = Convert.ToString(fldPres.LookupValue);

                        ddlDivPres.Text = Convert.ToString(fldPres.LookupValue);
                    }

                }

            }
            catch (Exception ex)
            {

            }

        }


        private void SetUserProfiles()
        {
            string currentUser = SPContext.Current.Web.CurrentUser.ToString().Substring(SPContext.Current.Web.CurrentUser.ToString().IndexOf("\\") + 1);
            SPSite spSite = SPContext.Current.Site;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                System.Web.HttpContext currentContext = System.Web.HttpContext.Current;
                System.Web.HttpContext.Current = null;
                try
                {
                    // Set the context of the site to the SPSite site
                    SPServiceContext context = SPServiceContext.GetContext(spSite);
                    //Create and instance of the UserProfileManager
                    UserProfileManager profileManager = new UserProfileManager(context);
                    UserProfile userProfile = profileManager.GetUserProfile(currentUser);

                    userProfile["PreferredName"].Value = Convert.ToString(txtName.Text);
                    //userProfile["Nationality"].Value = Convert.ToString(ddlNationality.SelectedItem.Text);
                    //userProfile["EmployeeID"].Value = Convert.ToString(txtEmployeeNo.Text);
                    //userProfile["DOB"].Value = Convert.ToString(dtDOB.SelectedDate.Date);
                    //userProfile["CellPhone"].Value = Convert.ToString(txtTelNo.Text);
                    //userProfile["PassportNo"].Value = Convert.ToString(txtEmployeeNo.Text);
                    //userProfile["PassportExpireOn"].Value = Convert.ToString(dtPassValidity.SelectedDate.Date);
                    //userProfile["DOJ"].Value = Convert.ToString(dtDOE.SelectedDate.Date);
                    // userProfile["QatarID"].Value = Convert.ToString(txtEmployeeNo.Text);

                    userProfile.Commit();

                }
                catch (SPException ex)
                {
                }
                finally
                {
                    System.Web.HttpContext.Current = currentContext;
                }

            });

        }


        private void GetApprovedUsers(string refNo)
        {
            SPListItemCollection oItemColl = null;
            string camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + refNo + "</Value></Eq></Where>";
            oItemColl = obj.GetSPListItems(SiteURL, TaskLstName, camlQry);
            DataTable dt = new DataTable();
            // dt.Columns.Add("Approved By");
            DataRow dr;

            using (SPSite oSite = new SPSite(SiteURL))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    if (oItemColl.Count > 0)
                    {
                        foreach (SPListItem oItem in oItemColl)
                        {
                            SPFieldUserValue fldUser = new SPFieldUserValue(oWeb, Convert.ToString(oItem["AssignedTo"]));
                            dt.Columns.Add(oItem["ID"].ToString());
                        }

                        dr = dt.NewRow();
                        int wfCnt = dt.Columns.Count;
                        int i = 0;
                        foreach (SPListItem oItem in oItemColl)
                        {
                            if (i < wfCnt)
                            {
                                SPFieldUserValue fldUser = new SPFieldUserValue(oWeb, Convert.ToString(oItem["AssignedTo"]));
                                if (Convert.ToString(fldUser.LookupValue).Contains("\\"))
                                {
                                    string user = Convert.ToString(fldUser.LookupValue);
                                    string[] users = user.Split('\\');
                                    int arrLenth = users.Length;
                                    if (arrLenth > 0)
                                        dr[i] = users[1];
                                    else
                                        dr[i] = users[0];
                                }
                                i++;
                            }
                        }
                        dt.Rows.Add(dr);
                        i = 0;
                        dr = dt.NewRow();
                        while (i < wfCnt)
                        {
                            dr[i] = "Approved By";
                            i++;
                        }
                        dt.Rows.Add(dr);
                        gvApprovers.DataSource = dt;
                        gvApprovers.DataBind();
                        gvApprovers.HeaderRow.Visible = false;
                    }

                }

            }

        }


    }
}
